
<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="utf-8">
        <title>浏览页面</title>
        <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
        <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    </head>
    <style>
        .layui-layer-shade {
            background-color: rgb(255 255 255) !important;
            opacity: 0.9;
        }
    </style>

    <body class="pear-container">
    
        <!-- 顶部查询表单 -->
        <div class="layui-card">
            <div class="layui-card-body">
                <form class="layui-form top-search-from">
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">主键</label>
                        <div class="layui-input-block">
                            <input type="number" name="id" value="" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-block">
                            <div name="status" id="status" value="" ></div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">是否生产</label>
                        <div class="layui-input-block">
                            <div name="is_product" id="is_product" value="" ></div>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">创建时间</label>
                        <div class="layui-input-block">
                            <div class="layui-input-block" id="created_at">
                                <input type="text" autocomplete="off" name="created_at[]" id="created_at-date-start" class="layui-input inline-block" placeholder="开始时间">
                                -
                                <input type="text" autocomplete="off" name="created_at[]" id="created_at-date-end" class="layui-input inline-block" placeholder="结束时间">
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label"></label>
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                            <i class="layui-icon layui-icon-search"></i>查询
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                            <i class="layui-icon layui-icon-refresh"></i>重置
                        </button>
                    </div>
                    <div class="toggle-btn">
                        <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                        <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="data-table" lay-filter="data-table"></table>
            </div>
        </div>

        <!-- 表格顶部工具栏 -->
        <script type="text/html" id="table-toolbar">
            <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add" permission="app.admin.carqrcode.insert">
                <i class="layui-icon layui-icon-add-1"></i>新增
            </button>
            <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="download" permission="app.admin.carqrcode.insert">
                <i class="layui-icon layui-icon-download-circle"></i>下载小程序码
            </button>
            <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="generate" permission="app.admin.carqrcode.insert">
                <i class="layui-icon layui-icon-link"></i>生成小程序码
            </button>
            <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="app.admin.carqrcode.delete">
                <i class="layui-icon layui-icon-delete"></i>删除
            </button>
        </script>

        <!-- 表格行工具栏 -->
        <script type="text/html" id="table-bar">
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.carqrcode.update">编辑</button>
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.carqrcode.delete">删除</button>
        </script>

        <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
        <script src="/app/admin/component/pear/pear.js"></script>
        <script src="/app/admin/admin/js/permission.js"></script>
        <script src="/app/admin/admin/js/common.js"></script>
        
        <script>

            // 相关常量
            const PRIMARY_KEY = "id";
            const SELECT_API = "/app/admin/car-qrcode/select";
            const UPDATE_API = "/app/admin/car-qrcode/update";
            const DELETE_API = "/app/admin/car-qrcode/delete";
            const GENERATE_API = "/app/admin/car-qrcode/generate";
            const DOWNLOAD_API  = "/app/admin/car-qrcode/download";
            const INSERT_URL = "/app/admin/car-qrcode/insert";
            const UPDATE_URL = "/app/admin/car-qrcode/update";
            
            // 字段 状态 status
            layui.use(["jquery", "xmSelect"], function() {
                let value = layui.$("#status").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#status",
                    name: "status",
                    filterable: true,
                    initValue: initValue,
                    data: [{"value":"0","name":"未生成"},{"value":"1","name":"待使用"},{"value":"2","name":"使用中"},{"value":"3","name":"已禁用"}],
                    model: {"icon":"hidden","label":{"type":"text"}},
                    clickClose: true,
                    radio: true,
                })
            });



            // 字段 状态 status
            layui.use(["jquery", "xmSelect"], function() {
                let value = layui.$("#is_product").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#is_product",
                    name: "is_product",
                    filterable: true,
                    initValue: initValue,
                    data: [{"value":"0","name":"全部"},{"value":"1","name":"未生产"},{"value":"2","name":"已生产"}],
                    model: {"icon":"hidden","label":{"type":"text"}},
                    clickClose: true,
                    radio: true,
                })
            });

            
            // 字段 创建时间 created_at
            layui.use(["laydate"], function() {
                layui.laydate.render({
                    elem: "#created_at",
                    range: ["#created_at-date-start", "#created_at-date-end"],
                    type: "datetime",
                });
            })
            
            // 表格渲染
            layui.use(["table", "form", "common", "popup", "util","layer"], function() {
                let table = layui.table;
                let form = layui.form;
                let $ = layui.$;
                let common = layui.common;
                let util = layui.util;
                let layer = layui.layer;
                
				// 表头参数
				let cols = [
					{
						type: "checkbox",
						align: "center"
					},{
						title: "主键",align: "center",
						field: "id",
						sort: true,
					},{
						title: "用户ID",align: "center",
						field: "user_id",
					},{
                        title: "主手机号",align: "center",
                        field: "phone",
                    },{
                        title: "备用手机号",align: "center",
                        field: "backup_phone",
                    },{
                        title: "是否开启隐私包含",align: "center",
                        field: "is_privacy",
                        templet: function (d) {
                            let field = "is_privacy";
                            if (typeof d[field] == "undefined") return "";
                            let items = [];
                            layui.each((d[field] + "").split(","), function (k , v) {
                                items.push(apiResults[field][v] || v);
                            });
                            return items.join(",");
                        }
                    },{
						title: "小程序码",align: "center",
						field: "qrcode",
						templet: function (d) {
							return '<img src="'+encodeURI(d['qrcode'])+'" style="max-width:32px;max-height:32px;" alt="" />'
						}
					},{
						title: "状态",align: "center",
						field: "status",
						templet: function (d) {
							let field = "status";
							if (typeof d[field] == "undefined") return "";
							let items = [];
							layui.each((d[field] + "").split(","), function (k , v) {
								items.push(apiResults[field][v] || v);
							});
							return items.join(",");
						}
					},{
						title: "是否生产",align: "center",
						field: "is_product",
						templet: function (d) {
							let field = "is_product";
							if (typeof d[field] == "undefined") return "";
							let items = [];
							layui.each((d[field] + "").split(","), function (k , v) {
								items.push(apiResults[field][v] || v);
							});
							return items.join(",");
						}
					},{
                        title: "备注",align: "center",
                        field: "remarks",
                    },{
						title: "创建时间",align: "center",
						field: "created_at",
						sort: true,
					}/*,{
						title: "更新时间",align: "center",
						field: "updated_at",
					}*/,{
						title: "操作",
						toolbar: "#table-bar",
						align: "center",
						fixed: "right",
						width: 120,
					}
				];
				
				// 渲染表格
				table.render({
				    elem: "#data-table",
				    url: SELECT_API,
                    page: {
                        limits: [10, 20, 50, 100,1000], // 可选每页条数（下拉选择）
                        limit: 50 // 默认每页显示 50 条
                    },
				    cols: [cols],
				    skin: "line",
				    size: "lg",
				    toolbar: "#table-toolbar",
				    autoSort: false,
				    defaultToolbar: [{
				        title: "刷新",
				        layEvent: "refresh",
				        icon: "layui-icon-refresh",
				    }, "filter", "print", "exports"],
				    done: function () {
				        layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});
				    }
				});
				
				// 获取表格中下拉或树形组件数据
				let apiResults = {};
				apiResults["status"] = ['<span style=\'color: red\'>未生成</span>','<span style=\'color: blue\'>待使用</span>','<span style=\'color: green\'>已使用</span>','<span style=\'color: red\'>已禁用</span>'];

                apiResults["is_product"] = ["全部",'<span style=\'color: grey\'>未生产</span>','<span style=\'color: green\'>已生产</span>'];
                apiResults["is_privacy"] = ['<span style=\'color: red\'>未开启</span>','<span style=\'color: green\'>已开启</span>'];
                // 编辑或删除行事件
                table.on("tool(data-table)", function(obj) {
                    if (obj.event === "remove") {
                        remove(obj);
                    } else if (obj.event === "edit") {
                        edit(obj);
                    }
                });

                // 表格顶部工具栏事件
                table.on("toolbar(data-table)", function(obj) {
                    if (obj.event === "add") {
                        add();
                    } else if (obj.event === "refresh") {
                        refreshTable();
                    } else if (obj.event === "batchRemove") {
                        batchRemove(obj);
                    }else if (obj.event === "generate") {
                        generate(obj);
                    }else if (obj.event === "download") {
                        download(obj);
                    }
                });

                // 表格顶部搜索事件
                form.on("submit(table-query)", function(data) {
                    table.reload("data-table", {
                        page: {
                            curr: 1
                        },
                        where: data.field
                    })
                    return false;
                });
                
                // 表格顶部搜索重置事件
                form.on("submit(table-reset)", function(data) {
                    table.reload("data-table", {
                        where: []
                    })
                });
                
                // 字段允许为空
                form.verify({
                    phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
                    email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
                    url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
                    number: [/(^$)|^\d+$/,'只能填写数字'],
                    date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
                    identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
                });

                // 表格排序事件
                table.on("sort(data-table)", function(obj){
                    table.reload("data-table", {
                        initSort: obj,
                        scrollPos: "fixed",
                        where: {
                            field: obj.field,
                            order: obj.type
                        }
                    });
                });

                // 表格新增数据
                let add = function() {
                    layer.open({
                        type: 2,
                        title: "新增",
                        shade: 0.1,
                        maxmin: true,
                        area: [common.isModile()?"100%":"500px", common.isModile()?"100%":"450px"],
                        content: INSERT_URL
                    });
                }

                // 表格编辑数据
                let edit = function(obj) {
                    let value = obj.data[PRIMARY_KEY];
                    layer.open({
                        type: 2,
                        title: "修改",
                        shade: 0.1,
                        maxmin: true,
                        area: [common.isModile()?"100%":"500px", common.isModile()?"100%":"450px"],
                        content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value
                    });
                }

                // 删除一行
                let remove = function(obj) {
                    return doRemove(obj.data[PRIMARY_KEY]);
                }

                // 删除多行
                let batchRemove = function(obj) {
                    let checkIds = common.checkField(obj, PRIMARY_KEY);
                    if (checkIds === "") {
                        layui.popup.warning("未选中数据");
                        return false;
                    }
                    doRemove(checkIds.split(","));
                }

                // 生成小程序码
                let generate = function(obj) {
                    let checkIds = common.checkField(obj, PRIMARY_KEY);
                    if (checkIds === "") {
                        layui.popup.warning("未选中数据");
                        return false;
                    }
                    doGenerate(checkIds.split(","));
                }


                 // 生成小程序码
                let download = function(obj) {
                    let checkIds = common.checkField(obj, PRIMARY_KEY);
                    if (checkIds === "") {
                        layui.popup.warning("未选中数据");
                        return false;
                    }
                    doDownload(checkIds.split(","));
                }

                // 执行删除
                let doRemove = function (ids) {
                    let data = {};
                    data[PRIMARY_KEY] = ids;
                    layer.confirm("确定删除?", {
                        icon: 3,
                        title: "提示"
                    }, function(index) {
                        layer.close(index);
                        let loading = layer.load();
                        $.ajax({
                            url: DELETE_API,
                            data: data,
                            dataType: "json",
                            type: "post",
                            success: function(res) {
                                layer.close(loading);
                                if (res.code) {
                                    return layui.popup.failure(res.msg);
                                }
                                return layui.popup.success("操作成功", refreshTable);
                            }
                        })
                    });
                }



                // 执行生成
                let doGenerate = function (ids) {
                    let data = {};
                    data[PRIMARY_KEY] = ids;
                    layer.confirm("确定生成?", {
                        icon: 3,
                        title: "提示"
                    }, function(index) {
                        layer.close(index);
                        let loading = layer.load();
                        $.ajax({
                            url: GENERATE_API,
                            data: data,
                            dataType: "json",
                            type: "post",
                            success: function(res) {
                                layer.close(loading);
                                if (res.code) {
                                    return layui.popup.failure(res.msg);
                                }
                                return layui.popup.success("操作成功", refreshTable);
                            }
                        })
                    });
                }


                // 执行下载
                let doDownload = function (ids) {
                    if (!ids || ids.length === 0) {
                        return layui.popup.failure('请选择要下载的图片');
                    }

                    layer.confirm("确定下载?", {
                        icon: 3,
                        title: "提示"
                    }, function(index) {
                        layer.close(index);

                        // 创建一个隐藏表单，模拟POST提交
                        let form = $('<form></form>');
                        form.attr('method', 'post');
                        form.attr('action', DOWNLOAD_API);
                        form.attr('target', '_blank'); // 新窗口打开触发浏览器下载

                        ids.forEach(id => {
                            // 主键是数组形式提交，如 id[]
                            let input = $('<input>')
                                .attr('type', 'hidden')
                                .attr('name', PRIMARY_KEY + '[]')
                                .val(id);
                            form.append(input);
                        });

                        // 将表单加到页面，提交后立即移除
                        $('body').append(form);
                        form.submit();
                        form.remove();

                        layui.popup.success("下载已开始");
                    });
                }

                // 刷新表格数据
                window.refreshTable = function() {
                    table.reloadData("data-table", {
                        scrollPos: "fixed",
                        done: function (res, curr) {
                            if (curr > 1 && res.data && !res.data.length) {
                                curr = curr - 1;
                                table.reloadData("data-table", {
                                    page: {
                                        curr: curr
                                    },
                                })
                            }
                        }
                    });
                }
            })

        </script>
    </body>
</html>
